#!/bin/sh /etc/rc.common
START=95

RUN_D=/var/run
PID_F=$RUN_D/miniupnpd.pid
CTL_F=$RUN_D/miniupnpd.ctl

append_bool() {
	local section="$1"
	local option="$2"
	local value="$3"
	local default="${4:-0}"
	local _loctmp
	config_get_bool _loctmp "$section" "$option" "$default"
	[ "$_loctmp" -gt 0 ] && append args "$3"
}

append_parm() {
	local section="$1"
	local option="$2"
	local switch="$3"
	local default="$4"
	local _loctmp
	config_get _loctmp "$section" "$option"
	[ -z "$_loctmp" ] && _loctmp="$default"
	[ -n "$_loctmp" ] && append args "$switch$_loctmp"
}

start() {
	[ -d "$RUN_D" ] || mkdir -p "$RUN_D"
	[ -f "$PID_F" ] && stop
	local enable ext_ifname ifup_interfaces iface ifname ipaddr donotlisten
	local upnpd_down_bitspeed upnpd_up_bitspeed
	local upnpd_down_bytespeed upnpd_up_bytespeed log_output

	config_load upnpd
	config_get_bool enable general enable 0
	[ "$enable" -gt 0 ] || return

	unset args
	config_get ext_ifname general ext_ifname
	[ -z "$ext_ifname" ] && ext_ifname=$(nvram get wan_ifname)
	append args "-i $ext_ifname"

	ifup_interfaces=$(nvram get ifup_interfaces)
	ifup_interfaces=${ifup_interfaces:-"lan wan wifi"}
	for iface in $ifup_interfaces; do
		if [ "$iface" != "wan" ]; then
			config_get_bool donotlisten "$iface" disable 0
			[ "$donotlisten" -gt 0 ] || {
				for ifname in $(nvram get "${iface}_ifname"); do
					for ipaddr in $(ifconfig "$ifname" 2>/dev/null | grep "inet addr:" | cut -d: -f 2 | cut -d' ' -f 1); do
						append args "-a $ipaddr"
					done
				done
			}
		fi
	done

	append_parm general port "-p " "5555"
	append_bool general system_uptime "-U" "1"
	append_bool general secure_mode "-S" "1"
	append_bool general nat_pmp "-N" "0"
	append_parm general uuid "-u " "fc4ec57e-b051-11db-88f8-0060085db3f6"
	append_parm general serial "-s " "12345678"
	append_parm general model_number "-m " "1"
	append_parm general notify_interval "-t " "30"
	append_parm general url "-w "
	config_get upnpd_down_bitspeed general download
	config_get upnpd_up_bitspeed general upload
	[ -n "$upnpd_down_bitspeed" ] && [ -n "$upnpd_up_bitspeed" ] && {
		upnpd_down_bytespeed=$(($upnpd_down_bitspeed * 1024 / 8))
		upnpd_up_bytespeed=$(($upnpd_up_bitspeed * 1024 / 8))
		append args "-B $upnpd_down_bytespeed $upnpd_up_bytespeed"
	}
	config_get_bool log_output general log_output 0
	iptables_init.sh >/dev/null 2>&1
	if [ "$log_output" -gt 0 ]; then
		miniupnpd $args -P "$PID_F" -d | logger miniupnpd &
	else
		miniupnpd $args -P "$PID_F"
	fi
	unset args
}

stop() {
	local pid_f
	iptables_flush.sh >/dev/null 2>&1
	[ -f "$PID_F" ] && pid_f=$(cat "$PID_F" 2>/dev/null) && [ -n "$pid_f" ] && {
		kill "$pid_f"
		rm -f "$PID_F" 2>/dev/null
	}
	[ -f "$CTL_F" ] && rm -f "$CTL_F" 2>/dev/null
	iptables_removeall.sh >/dev/null 2>&1
}
